package cn.hiapi.shop.api;

import cn.hiapi.basic.ResUtils;
import cn.hiapi.basic.controller.BasicQueryController;
import cn.hiapi.basic.security.TokenGet;
import cn.hiapi.basic.token.Token;
import cn.hiapi.finance.entity.Withdraw;
import cn.hiapi.finance.service.WithdrawService;
import cn.hiapi.finance.vo.WithdrawVO;
import cn.hiapi.interfaces.DispatchContext;
import cn.hiapi.shop.query.ShopWithdrawQuery;
import cn.hiapi.shop.service.shop.ShopLinkUserService;
import cn.hiapi.shopkeeper.consts.AppConst;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author AdinZ
 * @date 2023/2/27 16:46
 */
@RestController
@RequestMapping("/shop/withdraw")
public class ShopWithdrawController extends BasicQueryController<Withdraw,Long,WithdrawVO, ShopWithdrawQuery> {

    protected ShopWithdrawController(WithdrawService basicService, DispatchContext dispatchContext) {
        super(basicService, dispatchContext);
    }


    @Override
    public ShopWithdrawQuery setQuery(ShopWithdrawQuery query) {
        Token<Object> token = TokenGet.get();
        query.setFid(query.getShopId());
        this.dispatchContext.getServiceOne(ShopLinkUserService.class).verifyShop(token.getFid(), query.getShopId(), AppConst.SHOP_ROLE_AMOUNT);
        return super.setQuery(query);
    }

    @Override
    public List<WithdrawVO> toListVo(List<Withdraw> list, String[] fields) {
        if (list == null || list.size() == 0) return new ArrayList<>();
        return list.stream().map(e -> this.toData(e, fields)).collect(Collectors.toList());
    }

    @Override
    public WithdrawVO toData(Withdraw data, String[] fields) {
        WithdrawVO vo = new WithdrawVO();
        BeanUtils.copyProperties(data, vo);
        if (data.getStatus() != null)
            vo.setState(data.getStatus().name());
        try {
            if (!StringUtils.isEmpty(data.getDataJson())) {
                vo.setData(JSON.parseObject(data.getDataJson()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (!StringUtils.isEmpty(data.getBankcard())) {
                vo.setBank(JSON.parseObject(data.getBankcard()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        vo.setAmount(ResUtils.decimal(data.getAmount(), 2));
        vo.setTotalAmount(ResUtils.decimal(data.getTotalAmount(),2));
        vo.setTaxRate(ResUtils.decimal(data.getTaxRate(),2));
        vo.setTaxFee(ResUtils.decimal(data.getTaxFee(),2));
        return vo;
    }
}
